<?php
namespace app\system\controller;

use app\common\model\BuildLogic;
use app\common\model\FieldLogic;
use app\common\model\MoudleModel;
use org\util\FileUtil;
use think\helper\Str;
use think\Request;

class MoudleController extends BaseController
{

    private $moudleModel;

    /**
     * 初始化
     */
    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->moudleModel = new MoudleModel();
    }

    /**
     * 首页
     * @return mixed
     */
    public function index()
    {
        $list = $this->moudleModel->order('moudle_sort asc')->select();
        $this->assign('list', $list);
        return $this->fetch();
    }

    /**
     * 添加
     * @return mixed
     */
    public function add()
    {
        if ($this->request->isAjax()) {
            try{
                $data   = $this->request->param();
                $result = $this->validate($data, [
                    'moudle_name|模型名称' => 'require',
                    'table_name|模型表名'  => 'require|alphaDash',
                ]);
                if (true !== $result) {
                    exception($result,40001);
                }
                $this->moudleModel->addData($data);
                $this->moudleModel->updateCache();
                $this->moudleModel->updateTableCache($this->moudleModel->mid);
            } catch (\Exception $e){
                $this->error($e->getMessage());
            }
            $this->success('添加成功！', url('index'));
        }
        return $this->fetch();
    }

    /**
     * 修改数据
     * @return mixed
     */
    public function edit()
    {
        if ($this->request->isAjax()) {
            try{
                $data   = $this->request->param();
                $result = $this->validate($data, [
                    'moudle_name|模型名称' => 'require',
                ]);
                if (true !== $result) {
                    exception($result,40001);
                }
                $this->moudleModel->editData($data);
                $this->moudleModel->updateCache();
                $this->moudleModel->updateTableCache($data['mid']);
            } catch (\Exception $e){
                $this->error($e->getMessage());
            }
            $this->success('修改成功！', url('index'));
        }
        $mid  = $this->request->param('mid/d');
        $info = $this->moudleModel->get($mid);
        $this->assign('info', $info);
        return $this->fetch();
    }

    /**
     * 删除数据
     */
    public function del()
    {
        $mid = $this->request->param('mid', 0);
        try{
            $this->moudleModel->delData($mid);
            $this->moudleModel->updateCache();
            $this->moudleModel->updateTableCache($mid);
        } catch (\Exception $e){
            $this->error($e->getMessage());
        }
        $this->success('删除成功！');
    }

    /**
     * 更新缓存
     */
    public function updateCache()
    {
        try{
            $mids = $this->moudleModel->column('mid');
            $this->moudleModel->updateCache();
            foreach($mids as $mid){
                $this->moudleModel->updateTableCache($mid);
            }
        } catch (\Exception $e){
            $this->error($e->getMessage());
        }
        $this->success('更新缓存成功！');
    }

    /**
     * 生成模型
     */
    public function buildModel()
    {
        $buildLogic = new BuildLogic();
        $filepath   = 'app/common/model/logic/';
        if ($this->request->isAjax()) {
            try{
                $mid      = $this->request->param('mid');
                $filename = $this->request->param('filename');
                $filepath = $this->request->param('filepath');
                $file = $filepath.$filename;
                $bakfile = $filepath.'bak/'.str_replace('.php',date('YmdHis').'.php',$filename);
                if(file_exists($file)){ //模型文件已存在，备份
                    FileUtil::copyFile($file,$bakfile);
                }
                $content  = $buildLogic->buildModel($mid);
                $result   = file_put_contents($file, '<?php' . PHP_EOL . $content);
                if ($result === false) {
                    exception('服务器目录不可写',40001);
                } else {
                    $this->moudleModel->where('mid', $mid)->setField('model_tpl', 1);//更新模型状态
                }
            } catch (\Exception $e){
                $this->error($e->getMessage());
            }
            $this->success('生成成功！', url('index', ['mid' => $mid]));
        }
        $mid        = $this->request->param('mid');
        $moudleInfo = $this->moudleModel->get($mid);
        $filename   = Str::studly($moudleInfo['table_name']) . 'Model.php';
        switch ($moudleInfo->model_tpl) {
            case 0:
                $infoMsg = '模型文件还未初始化！';
                break;
            case 1:
                $infoMsg = '模型文件已存在，重新生成会覆盖原模型文件。！';
                break;
        }
        $content = htmlspecialchars($buildLogic->buildModel($mid));
        $this->assign('infoMsg', $infoMsg);
        $this->assign('filepath', $filepath);
        $this->assign('filename', $filename);
        $this->assign('moudleInfo', $moudleInfo);
        $this->assign('content', $content);
        return $this->fetch();
    }

    /**
     * 生成静态页面
     */
    public function buildHtml(){
        $mid = $this->request->param('mid');
        $tpl = $this->request->param('tpl');
        $moudle = $this->moudleModel->where('mid',$mid)->find();
        if($tpl=='list_tpl'){
            if($moudle['is_bind']==1){
                $html = $this->buildCmsListTpl();
            }else{
                $html = $this->buildOListTpl();
            }
        }
        if($tpl=='add_tpl'){
            $html = $this->buildAddTpl($moudle['table_name']);
        }
        if($tpl=='edit_tpl'){
            $html = $this->buildEditTpl($moudle['table_name']);
        }
        $html=htmlspecialchars($html);
        $this->assign('html',$html);
        return $this->fetch();
    }

    //生成cms列表页
    private function buildCmsListTpl(){
        $html = <<<CODE
{extend name="public:layout" /}
{block name="title"}{\$moudleName}列表{/block}
{block name="head"}{/block}
{block name="body"}
<div class="wrapper wrapper-content">
    <div class="ibox">
        <div class="ibox-title">
            <ol class="breadcrumb">
                <ol class="breadcrumb">
                    <li class="active"><i class="fa fa-hand-o-right"></i> {\$moudleName}列表</li>
                </ol>
            </ol>
        </div>
        <div class="ibox-content">
            <div class="toolbar">
                <div class="pull-left">
                    <button type="button" onclick="CheckAll();" class="btn btn-white">全</button>
                    <button type="button" onclick="CheckOther();" class="btn btn-white">反</button>
                    <a class="btn btn-primary"
                       href="{:url('add',['mid'=>\$Request.param.mid,'cid'=>\$Request.param.cid])}">
                        <i class="fa fa-plus"></i>&nbsp;添加{\$moudleName}
                    </a>
                </div>
                <div class="pull-right">
                    <form class="form-inline" id="searchForm" method="post">
                        <input name="cid" type="hidden" />
                        <div class="form-group">
                            <select class="form-control" id="locatlCid">
                                <option value="">快速跳转</option>
                                {volist name="category" id="vo"}
                                <option value="{\$vo.cid}" {eq name="query.cid" value="\$vo['cid']"}selected{/eq}>{\$vo._name}</option>
                                {/volist}
                            </select>
                        </div>
                        <div class="form-group">
                            <div class="input-group">
                                <input class="form-control" type="text" placeholder="请输入检索标题"
                                       name="title" value="{\$query.title}"/>
                            </div>
                        </div>
                        <button type="submit" class="btn btn-info">
                            <i class="fa fa-search"></i> 搜索
                        </button>
                        <a class="btn btn-white" href="{:url('index',['mid'=>\$Request.param.mid])}">
                            <i class="fa fa-trash"></i> 清空
                        </a>
                    </form>
                </div>
                <div class="clearfix"></div>
            </div>
            <table class="table table-bordered" id="grid">
                <thead>
                <tr>
                    <th width="50">#</th>
                    <th width="70">排序</th>
                    <th>标题</th>
                    <th width="200">绑定模板<span style="font-weight:500;font-size:12px;">(非技术人员请勿修改)</span></th>
                    <th width="80">操作</th>
                </tr>
                </thead>
                <tbody>
                {volist name="list" id="vo"}
                <tr>
                    <td>
                        <input name="aid[]" type="checkbox" class="checkbox" value="{\$vo.aid}" />
                    </td>
                    <td>
                        <input type="text" class="form-control input-sm batchSort" value="{\$vo.sort}"
                               name="sort[{\$vo.aid}]" />
                    </td>
                    <td>{\$vo.title}</td>
                    <td>
                        <input type="text" class="form-control input-sm content-tpl" value="{\$vo.content_tpl}"
                               name="tpl[{\$vo.aid}]" />
                    </td>
                    <td>
                        <a href="{:url('edit',['aid'=>\$vo['aid'],'mid'=>\$vo['mid'],'cid'=>\$vo['cid']])}">编辑</a>
                        <a href="javascript:;" onclick="doAction(this);"
                           data-msg="确认删除吗？" data-url="{:url('del')}" data-params="aid={\$vo.aid}&mid={\$vo.mid}">删除</a>
                    </td>
                </tr>
                {/volist}
                </tbody>
            </table>
            <div class="p8">
                <div class="pull-left">
                    <div class="form-inline">
                        <button type="button" onclick="upOrder();" class="btn btn-info">
                            <i class="fa fa-sort"></i> 排序
                        </button>
                        <button type="button" onclick="batchDel(CheckboxValue())" class="btn btn-danger">
                            <i class="fa fa-trash"></i> 删除
                        </button>
                        <button type="button" onclick="setTpl();" class="btn btn-info">
                            <i class="fa fa-bookmark"></i> 设置模板
                        </button>
                    </div>
                </div>
                <div class="page-bar">{\$list->render()}</div>
                <div class="clearfix"></div>
            </div>
        </div>
    </div>
</div>
{/block}
{block name="script"}
<script type="text/javascript">
    $(function () {
        $('#locatlCid').change(function () {
            var cid=$(this).val();
            $("input[name='cid']").val(cid);
            $('#searchForm').submit();
        });
    });
    //批量删除文章
    function batchDel(aid) {
        if (IsMore(aid)) {
            var url = "{:url('del')}";
            var params = {'aid': aid, 'mid': "{\$Request.param.mid}"};
            doConfirm('你确认要删除吗？', url, params, function (data) {
                if (data.code == 1) {
                    rePage();
                }
            });
        }
    }
    //更新排序
    function upOrder() {
        if ($(".batchSort").length == 0) {
            alert('您还没有添加内容！');
            return false;
        }
        var params = $(".batchSort").serialize();
        var url = "{:url('upOrder',['mid'=>\$Request.param.mid])}";
        getAjax(url, params, function (data) {
            if (data.code == 1) {
                rePage();
            }
        });
    }
    //批量设置模板
    function setTpl() {
        if ($(".content-tpl").length == 0) {
            alert('您还没有添加内容！');
            return false;
        }
        var params = $(".content-tpl").serialize();
        var url = "{:url('setTpl',['mid'=>\$Request.param.mid])}";
        getAjax(url, params, function (data) {
            if (data.code == 1) {
                rePage();
            }
        });
    }
</script>
{/block}
CODE;
        return $html;
    }
    //生成cms列表页
    private function buildOListTpl(){
        $html = <<<CODE
{extend name="public:layout" /}
{block name="title"}{\$moudleName}列表{/block}
{block name="head"}{/block}
{block name="body"}
<div class="wrapper wrapper-content">
    <div class="ibox">
        <div class="ibox-title">
            <ol class="breadcrumb">
                <ol class="breadcrumb">
                    <li class="active"><i class="fa fa-hand-o-right"></i> {\$moudleName}列表</li>
                </ol>
            </ol>
        </div>
        <div class="ibox-content">
            <div class="toolbar">
                <div class="pull-left">
                    <button type="button" onclick="CheckAll();" class="btn btn-white">全</button>
                    <button type="button" onclick="CheckOther();" class="btn btn-white">反</button>
                    <a class="btn btn-primary"
                       href="{:url('add',['mid'=>\$Request.param.mid,'cid'=>\$Request.param.cid])}">
                        <i class="fa fa-plus"></i>&nbsp;添加{\$moudleName}
                    </a>
                </div>
                <div class="pull-right">
                    <form class="form-inline" id="searchForm" method="post">
                        <div class="form-group">
                            <div class="input-group">
                                <input class="form-control" type="text" placeholder="请输入检索标题"
                                       name="title" value="{\$query.title}"/>
                            </div>
                        </div>
                        <button type="submit" class="btn btn-info">
                            <i class="fa fa-search"></i> 搜索
                        </button>
                        <a class="btn btn-white" href="{:url('index',['mid'=>\$Request.param.mid])}">
                            <i class="fa fa-trash"></i> 清空
                        </a>
                    </form>
                </div>
                <div class="clearfix"></div>
            </div>
            <table class="table table-bordered" id="grid">
                <thead>
                <tr>
                    <th width="50">#</th>
                    <th width="70">排序</th>
                    <th>标题</th>
                    <th width="80">操作</th>
                </tr>
                </thead>
                <tbody>
                {volist name="list" id="vo"}
                <tr>
                    <td>
                        <input name="aid[]" type="checkbox" class="checkbox" value="{\$vo.aid}" />
                    </td>
                    <td>
                        <input type="text" class="form-control input-sm batchSort" value="{\$vo.sort}"
                               name="sort[{\$vo.aid}]" />
                    </td>
                    <td>{\$vo.title}</td>
                    <td>
                        <a href="{:url('edit',['aid'=>\$vo['aid'],'mid'=>\$vo['mid'],'cid'=>\$vo['cid']])}">编辑</a>
                        <a href="javascript:;" onclick="doAction(this);"
                           data-msg="确认删除吗？" data-url="{:url('del')}" data-params="aid={\$vo.aid}&mid={\$vo.mid}">删除</a>
                    </td>
                </tr>
                {/volist}
                </tbody>
            </table>
            <div class="p8">
                <div class="pull-left">
                    <div class="form-inline">
                        <button type="button" onclick="upOrder();" class="btn btn-info">
                            <i class="fa fa-sort"></i> 排序
                        </button>
                        <button type="button" onclick="batchDel(CheckboxValue())" class="btn btn-danger">
                            <i class="fa fa-trash"></i> 删除
                        </button>
                    </div>
                </div>
                <div class="page-bar">{\$list->render()}</div>
                <div class="clearfix"></div>
            </div>
        </div>
    </div>
</div>
{/block}
{block name="script"}
<script type="text/javascript">
    //批量删除
    function batchDel(aid) {
        if (IsMore(aid)) {
            var url = "{:url('del')}";
            var params = {'aid': aid, 'mid': "{\$Request.param.mid}"};
            doConfirm('你确认要删除吗？', url, params, function (data) {
                if (data.code == 1) {
                    rePage();
                }
            });
        }
    }
    //更新排序
    function upOrder() {
        if ($(".batchSort").length == 0) {
            alert('您还没有添加内容！');
            return false;
        }
        var params = $(".batchSort").serialize();
        var url = "{:url('upOrder',['mid'=>\$Request.param.mid])}";
        getAjax(url, params, function (data) {
            if (data.code == 1) {
                rePage();
            }
        });
    }
</script>
{/block}
CODE;
        return $html;
    }
    //生成添加页
    private function buildAddTpl($tableName){
        $fieldLogic = new FieldLogic($tableName);
        $layoutForm = $fieldLogic->getHtml();
        $form='';
        foreach($layoutForm as $v){
            $form.='<div class="form-group">'.PHP_EOL;
            foreach($v as $h){
                $form.=$h['html'].PHP_EOL;
            }
            $form.='</div>'.PHP_EOL;
        }
        $html = <<<CODE
{extend name="public:layout" /}
{block name="title"}添加{\$moudleName}{/block}
{block name="head"}{/block}
{block name="body"}
<div class="wrapper wrapper-content">
    <div class="ibox">
        <div class="ibox-title">
            <ol class="breadcrumb">
                <li>
                    <i class="fa fa-hand-o-right"></i>
                    <a href="{:url('index',['mid'=>\$Request.param.mid,'cid'=>\$Request.param.cid])}">{\$moudleName}列表</a>
                </li>
                <li class="active">添加{\$moudleName}</li>
            </ol>
        </div>
        <div class="ibox-content">
            <form method="post" class="form-horizontal" id="form">
                {$form}
                <div class="form-group">
                    <div class="col-sm-10 col-sm-offset-2">
                        <button class="btn btn-primary" id="btnSub" type="button">保存</button>
                        <a href="{:url('index',['mid'=>\$Request.param.mid])}" class="btn btn-white">取消</a>
                        <span id="validError"></span>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
{/block}
{block name="script"}
<script type="text/javascript">
    $(function () {
        iCheck();
        formatDate();
        ajaxSubForm('#btnSub');
    });
</script>
{/block}
CODE;
        return $html;
    }
    //生成编辑页
    private function buildEditTpl($tableName){
        $fieldLogic = new FieldLogic($tableName);
        $info=['title'=>'占坑位'];
        $layoutForm = $fieldLogic->getHtml($info);
        $form='';
        foreach($layoutForm as $v){
            $form.='<div class="form-group">'.PHP_EOL;
            foreach($v as $h){
                $form.=$h['html'].PHP_EOL;
            }
            $form.='</div>'.PHP_EOL;
        }
        $html = <<<CODE
{extend name="public:layout" /}
{block name="title"}编辑{\$moudleName}{/block}
{block name="head"}{/block}
{block name="body"}
<div class="wrapper wrapper-content">
    <div class="ibox">
        <div class="ibox-title">
            <ol class="breadcrumb">
                <li>
                    <i class="fa fa-hand-o-right"></i>
                    <a href="{:url('index',['mid'=>\$Request.param.mid,'cid'=>\$Request.param.cid])}">{\$moudleName}列表</a>
                </li>
                <li class="active">编辑{\$moudleName}</li>
            </ol>
        </div>
        <div class="ibox-content">
            <form method="post" class="form-horizontal" id="form">
                {$form}
                <div class="form-group">
                    <div class="col-sm-10 col-sm-offset-2">
                        <button class="btn btn-primary" id="btnSub" type="button">保存</button>
                        <a href="{:url('index',['mid'=>\$Request.param.mid])}" class="btn btn-white">取消</a>
                        <span id="validError"></span>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
{/block}
{block name="script"}
<script type="text/javascript">
    $(function () {
        iCheck();
        formatDate();
        ajaxSubForm('#btnSub');
    });
</script>
{/block}
CODE;
        return $html;
    }
}
